package microcredit.gui.table;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Locale;

import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;

import microcredit.gui.util.NumericTextField;



public class BeanTableBigDecimalEditor extends AbstractCellEditor {

	private static DecimalFormat format = (DecimalFormat)DecimalFormat.getNumberInstance(Locale.ENGLISH);
	static {
		format.setMinimumFractionDigits(2);
		format.setMaximumFractionDigits(2);
		format.setParseBigDecimal(true);
	}
	
	public BeanTableBigDecimalEditor() {
		super(new NumericTextField(null, 10, format));
		setClickCountToStart(0);
	}

	private static final long serialVersionUID = 1L;

	@Override
	public Object getCellEditorValue() {
		String s = (String)super.getCellEditorValue();
		try {
			return format.parse(s);
		} catch (ParseException e) {
			return null;
		}
	}
	
	@Override
	public Component getTableCellEditorComponent(JTable table, Object value,
			boolean isSelected, int row, int column) {
		JTextField field = (JTextField)super.getTableCellEditorComponent(table, value, isSelected, row, column);
		
		EmptyBorder empty = new EmptyBorder(1, 3, 2, 2);
		Border matte = new EtchedBorder();
		CompoundBorder border = new CompoundBorder(matte, empty);
		field.setBorder(border);
		field.setHorizontalAlignment(JTextField.TRAILING);
		if (value == null) {
			field.setText("");
		} else {
			field.setText(format.format((BigDecimal)value));
		}
		field.requestFocus();
		field.selectAll();
		
		return field;
	}
	
	
}
